package io.wit.modules.sys.controller;

import io.wit.common.utils.PageUtils;
import io.wit.common.utils.Query;
import io.wit.common.utils.R;
import io.wit.config.ConfigFile;
import io.wit.modules.sys.entity.SysDeptEntity;
import io.wit.modules.sys.entity.SysUserEntity;
import io.wit.modules.sys.service.SysDeptService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 部门管理
*/
@RestController
@RequestMapping("/sys/dept")
public class SysDeptController extends AbstractController {

    @Autowired
	private SysDeptService sysDeptService;

    @Value("${platform_role_id}")
    private long role_id;

    @Value("${role_value2}")
    private int roleValue2;

    @Value("${role_value2}")
    private long value2;
	
	/**
	 * 列表
	*/
	@RequestMapping("/list")
	@RequiresPermissions("sys:dept:list")
	public List<SysDeptEntity> list(@RequestParam final Map<String, Object> params){
        final String userName = getUserName();
        final Long roleId = getRoleId();
        if(ConfigFile.KEY_SUPER.equals(userName) || roleId == role_id){//admin|平台运营管理|系统管理员的id标识,在添加用户账号时且不能获取部门列表
            return new ArrayList<SysDeptEntity>();
        }
        return getDeptList(params);
	}

    @GetMapping("/getList")
    @RequiresPermissions("sys:dept:list")
	public List<SysDeptEntity> getList(@RequestParam final Map<String, Object> params){
        return getDeptList(params);
    }

	/**
	 * 选择部门(添加、修改菜单)
	*/
	@RequestMapping("/select")
	@RequiresPermissions("sys:dept:select")
	public R select(@RequestParam final Map<String, Object> params){
        return R.ok().put("deptList",getDeptList(params));
	}

    private List<SysDeptEntity> getDeptList(final Map<String, Object> params){
        final SysUserEntity user = getUser();
        final Query query = new Query(params);
        if(user.getUsername().equals(ConfigFile.superUser)){
            return sysDeptService.queryList(query);//超级管理员
        }
        final Long subjectId = user.getSubjectId();
        if(subjectId != null){
            query.put("subjectId",subjectId);
            return sysDeptService.queryList(query);
        }else{
            return new ArrayList<SysDeptEntity>();
        }
    }

    @GetMapping("/getListData")
    @RequiresPermissions("sys:dept:list")
    public R getListData(@RequestParam final Map<String, Object> params){
        final Query query = new Query(params);
        final String userName = getUserName();
        final Long roleId = getRoleId();
        if(ConfigFile.KEY_SUPER.equals(userName) || roleId == value2){
            query.remove("subjectId");
            final List<SysDeptEntity> userList = sysDeptService.getListData(query);
            final int total = sysDeptService.getListTotal(query);
            final PageUtils page = new PageUtils(userList,total,query.getLimit(),query.getPage());
            return R.ok().put("page",page);
        }
        final Long subjectId = getSubjectId();
        if(subjectId != null){
            query.put("subjectId",subjectId);
            final List<SysDeptEntity> userList = sysDeptService.getListData(query);
            final int total = sysDeptService.getListTotal(query);
            final PageUtils page = new PageUtils(userList,total,query.getLimit(),query.getPage());
            return R.ok().put("page",page);
        }else{
            final PageUtils page = new PageUtils(new ArrayList<>(),0,query.getLimit(), query.getPage());
            return R.ok().put("page",page).put("msg","当前账号尚未添加经营主体");
        }
    }

    /**
	 * 默认获取最上层的部门id
	*/
	@RequestMapping("/info")
	@RequiresPermissions("sys:dept:list")
	public R info(){
        return R.ok().put("data",0);
	}
	
	/**
	 * 信息
	*/
	@RequestMapping("/info/{deptId}")
	@RequiresPermissions("sys:dept:info")
	public R info(@PathVariable("deptId") Long deptId){
        final HashMap<String,Object> params = new HashMap<>();
        params.put("deptId",deptId);
		final SysDeptEntity dept = sysDeptService.queryInfoObject(params);
		return R.ok().put("dept",dept);
	}
	
	/**
	 * 保存
	*/
	@RequestMapping("/save")
	@RequiresPermissions("sys:dept:save")
	public R save(@RequestBody SysDeptEntity dept){
        final SysUserEntity user = getUser();
        final R r = checkRole(user);
        if(r != null) return r;
        final String deptName = dept.getName();
        if(deptName == null || deptName.length() <= 0){
            return R.fail("部门名称不能为空");
        }
        dept.setSubjectId(user.getSubjectId());
        final int rows = sysDeptService.save(dept);
        return R.execute(rows);
	}
	
	/**
	 * 修改
	*/
	@RequestMapping("/update")
	@RequiresPermissions("sys:dept:update")
	public R update(@RequestBody SysDeptEntity dept){
        final SysUserEntity user = getUser();
        final R r = checkRole(user);
        if(r != null) return r;
        dept.setSubjectId(user.getSubjectId());
        final int rows = sysDeptService.update(dept);
        return R.execute(rows);
	}

	/**
	 * 启用
	*/
	@RequestMapping("/enable")
	@RequiresPermissions("sys:dept:update")
	public R enable(final Long deptId){
        final SysUserEntity user = getUser();
        final R r = checkRole(user);
        if(r != null) return r;
        final int rows = sysDeptService.enable(deptId);
        return R.execute(rows);
	}

	private R checkRole(final SysUserEntity user){
        if(filterPrivilege(roleValue2)){
            return R.invalidPrivilege();
        }
        final Long subjectId = user.getSubjectId();
        if(subjectId == null){
            return R.fail("你还未添加经营主体!");
        }
        return null;
    }
	
	/**
	 * 删除
	*/
	@RequestMapping("/delete")
	@RequiresPermissions("sys:dept:delete")
	public R delete(long deptId){
		//判断是否有子部门
		List<Long> deptList = sysDeptService.queryDetpIdList(deptId);
		if(deptList.size() > 0){
			return R.error("请先删除子部门");
		}
		sysDeptService.delete(deptId);
		return R.ok();
	}
}